<template>
  <div class="login_content">
    <el-form class="form_wrap" :model="formData" label-width="80px" :rules="rules" label-position="top" ref="form">
      <el-form-item label="账号" prop="userName">
        <el-input v-model="formData.userName"></el-input>
      </el-form-item>

      <el-form-item label="密码" prop="password">
        <el-input type="password" v-model="formData.password" />
      </el-form-item>

      <div class="confirm_pwd">
        <el-form-item v-if="!loginShow" label="确认密码" prop="confirmPwd">
          <el-input type="password" v-model="formData.confirmPwd"></el-input>
        </el-form-item>
      </div>

      <el-button class="confirm_btn" type="danger" @click="handleConfirm">确认</el-button>
    </el-form>

    <div class="btn_group">
      <span :class="{ active: loginShow }" @click="toggleClick">登录</span>
      <i>|</i>
      <span :class="{ active: !loginShow }" @click="toggleClick">注册</span>
    </div>
  </div>
</template>

<script>
import { reactive, ref, toRefs, onMounted, nextTick, getCurrentInstance } from 'vue';
import { login, register } from '@/api/login';
import { useRouter } from 'vue-router';
import { ElNotification } from 'element-plus';
import { setToken } from '@/utils/auth';

export default {
  name: 'Login',
  setup() {
    const state = reactive({
      loginShow: true,
      formData: {
        userName: '',
        password: '',
        confirmPwd: '',
      },
      rules: {
        userName: [{ required: true, message: '请输入账号', trigger: 'blur' }],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          {
            pattern: /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,20}$/,
            message: '密码为6-20位数字或字母，包含至少一个数字,一个字母',
            trigger: 'blur',
          },
        ],
        confirmPwd: [{ required: true, message: '请输入密码', trigger: 'blur' }],
      },
    });
    const form = ref(null);

    const router = useRouter();

    onMounted(() => {
      init();
    });

    const init = () => {
      const { ctx } = getCurrentInstance();
      state.loginShow = ctx.$router.currentRoute.value.query.action === 'login';
    };

    const toggleClick = () => {
      let action;
      state.loginShow = !state.loginShow;
      if (state.loginShow) {
        action = 'login';
      } else {
        action = 'register';
      }
      router.replace({
        path: '/login',
        query: {
          action,
        },
      });
    };

    const handleConfirm = () => {
      nextTick(() => {
        form.value.validate(async valid => {
          if (valid) {
            const { userName, password, confirmPwd } = state.formData;
            if (state.loginShow) {
              const { id, token } = await login({ userName, password });
              setToken('PAY-Token', token);
              setToken('PAY-UserId', id);
              ElNotification.success({ title: '登录成功' });
              router.push('/');
            } else {
              if (confirmPwd === password) {
                await register({ userName, password });
                ElNotification.success({ title: '注册成功' });
                toggleClick();
              } else {
                ElNotification.error({ title: '两次输入密码不一致' });
              }
            }
          }
        });
      });
    };

    return {
      ...toRefs(state),
      form,
      toggleClick,
      handleConfirm,
    };
  },
};
</script>

<style lang="scss" scoped>
.login_content {
  position: absolute;
  width: 322px;
  padding: 10px 20px;
  top: 10vh;
  right: 20px;
  background-color: #ffffff;
  border-radius: 10px;
  overflow: hidden;
  /deep/ .el-form {
  }

  .confirm_btn {
    width: 100%;
  }

  .btn_group {
    padding-right: 20px;
    text-align: right;
    span {
      font-size: 14px;
      line-height: 50px;
      cursor: pointer;
      &.active {
        color: rgb(210, 87, 30);
      }
    }
    i {
      margin: 0 10px;
      color: #999999;
    }
  }
}
</style>
